<?php

namespace App\Http\Controllers\RbhMiniProgram;

use Carbon\Carbon;
use App\Models\SupplyModel;
use App\Models\GoodsPicPrimaryModel;
use App\Utils\ApiResponse;
use App\Utils\VerifyRequestInput;
use App\Http\Controllers\Controller;
use App\Exceptions\BusinessException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hfm\BaiduAi\BaiduAI;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class MiniProgramSupplyController extends Controller
{
    use ApiResponse, VerifyRequestInput;

    /**
     * 获取商家列表
     * @return JsonResponse
     */
    public function getList(): JsonResponse
    {
        $paginate = SupplyModel::where('status', 1)
            ->select(['ID', 'CName', 'Manager', 'Mobile', 'Addr', 'datetime'])->orderBy('top')->paginate(10);
        $items = json_decode(json_encode($paginate->items()));
        $list = [];
        $goodsCollection = $this->getSupplyCollection($items);
        foreach ($items as $supply) {
            $supply->year = Carbon::today()->diffInYears(Carbon::parse($supply->datetime));
            $supply->goods  = $this->getSupplyLatestGoods($goodsCollection, $supply->ID);
            $list[] = $supply;
        }
        return $this->success(['total' => $paginate->total(), 'list' => $list]);
    }

    /**
     * 获取供应商信息
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getSupplyInfo(): JsonResponse
    {
        $sid = $this->verifyId('sid');
        $supply = SupplyModel::where('ID', $sid)->select(['ID', 'CName', 'Manager', 'Mobile', 'Addr', 'datetime'])->first();
        if ($supply) {
            $supply->year = Carbon::today()->diffInYears(Carbon::parse($supply->datetime));
            $supply->extend = DB::connection('rbh')->table('supply_extend')->where('sid', $sid)
                ->whereNotNull('business_company_name')->first();
        }
        return $this->success($supply);
    }

    /**
     * 营业执照图片解析
     * @return JsonResponse
     * @throws GuzzleException
     */
    public function parseBusinessLicenceToText(): JsonResponse
    {
        $item = DB::connection('rbh')->table('supply_extend')->whereNotNull('business_image')
            ->whereNull('business_company_name')->where('status', 0)->first();
        if ($item) {
            $img = file_get_contents('https://erp.toysmodel.cn:11443/storage/' . $item->business_image);
            if (!$img) {
                DB::connection('rbh')->table('supply_extend')->where('id', $item->id)->update(['status' => 2]);
                return $this->fail([20001, '营业执照图片解析失败']);
            } else {
                $data = $this->getResponseFromBaiduAi(base64_encode($img));
                if ($data)
                    $this->parseBusinessLicenceImageData($item->id, $data);
                return $this->success($data);
            }
        }
        return $this->fail([20001, '营业执照图片解析失败']);
    }

    /**
     * 百度AI交互
     * @param $imageData
     * @return string|null
     * @throws GuzzleException
     */
    private function getResponseFromBaiduAi($imageData): ?string
    {
        $AI = new BaiduAI('44946779', 'jk7cCd7yVH1R7G02DCslsiqr', 'hywd2k5WI83RpKdXlp1Pl4UzIVn2gn2r');
        $accessToken = $AI->getToken();
        if ($accessToken) {
            $client = new Client();
            $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/business_license?access_token=' . $accessToken;
            $response = $client->post($url, [
                'headers' => [
                    'Content-Type' => 'application/x-www-form-urlencoded',
                ],
                'form_params' => [
                    'image' => $imageData,
                ]
            ]);
            return $response->getBody()->getContents();
        }
        return null;
    }

    /**
     * 解析营业执照图片
     * @param $itemId
     * @param $data
     * @return void
     */
    private function parseBusinessLicenceImageData($itemId, $data): void
    {
        if ($data && $itemId) {
            $array = json_decode($data, true);
            if ($array && isset($array['words_result'])) {
                $saveData = [];
                foreach ($array['words_result'] as $key => $word) {
                    if ($key === '单位名称')
                        $saveData['business_company_name'] = $word['words'];
                    if ($key === '成立日期')
                        $saveData[ 'business_date'] = $word['words'];
                    if ($key === '注册资本')
                        $saveData['business_foundation'] = $word['words'];
                    if ($key === '法人')
                        $saveData['business_chairman'] = $word['words'];
                    if ($key === '社会信用代码')
                        $saveData['business_code'] = $word['words'];
                    if ($key === '有效期')
                        $saveData['business_expired'] = $word['words'];
                    if ($key === '经营范围')
                        $saveData['business_scope'] = $word['words'];
                    if ($key === '地址')
                        $saveData['business_address'] = $word['words'];
                }
                DB::connection('rbh')->table('supply_extend')->where('id', $itemId)->update($saveData);
            } else
                DB::connection('rbh')->table('supply_extend')->where('id', $itemId)->update(['status' => 2]);
        }
    }

    /**
     * 获取供应商商品集合
     * @param $suppliers
     * @return mixed
     */
    private function getSupplyCollection($suppliers): mixed
    {
        $sids = array_column($suppliers, 'ID');
        $date = Carbon::today()->subDays(90)->toDateString();
        return GoodsPicPrimaryModel::whereIn('SID', $sids)->where('ITime', '>=', $date)
            ->select('ID', 'SID', 'PName', 'Path', 'FName')->get();
    }

    /**
     * 从集合中获取供应商最新商品
     * @param $collection
     * @param $sid
     * @return array
     */
    private function getSupplyLatestGoods($collection, $sid): array
    {
        $supplyGoodsCollection = $collection->where('SID', $sid);
        $goods = [];
        if ($supplyGoodsCollection->isNotEmpty()) {
            foreach ($supplyGoodsCollection as $v) {
                if (count($goods) >= 3)
                    break;
                $v->thumbnail = self::DISK_HOST . self::THUMBNAIL_PATH . $v->Path . DIRECTORY_SEPARATOR . $v->FName;
                $goods[] = $v;
            }
        }
        return $goods;
    }
}
